package edu.ncut.vod.jsf.examonline.managedbeans;

import javax.faces.component.html.HtmlInputSecret;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseListener;

import edu.ncut.vod.exception.ExamException;

/**
 * public interface PhaseListener extends java.util.EventListener, java.io.Serializable:
 * An interface implemented by objects that wish to be notified at the beginning and ending of 
 * processing for each standard phase of the request processing lifecycle.
 */
public class LoginBean extends BaseBean implements PhaseListener{

    private static final long serialVersionUID = 2032662145679343782L;

    public LoginBean() {
        this.clear();
    }
    
    public void clear(){
        this.managerName = null;
        this.password = null;
    }

    /*
     * binding with tag h:inputText whose id is 'managerName'
     */
    private HtmlInputText managerName;

    public HtmlInputText getManagerName() {
        return managerName;
    }

    public void setManagerName(HtmlInputText managerName) {
        this.managerName = managerName;
    }

    /*
     * binding with tag h:inputText whose id is 'password'
     */
    private HtmlInputSecret password;

    public HtmlInputSecret getPassword() {
        return password;
    }

    public void setPassword(HtmlInputSecret password) {
        this.password = password;
    }
    
    /*
     * indicates what page we will forward.
     */
    private String redirect;    

    public String getRedirect() {
        return redirect;
    }

    public void setRedirect(String redirect) {
        this.redirect = redirect;
    }
    
    /**
     * method when clicking submit button to perform,which is a actionListener
     * @return
     */
    public void loginActionListener(ActionEvent event){
        String name = (String)getManagerName().getValue();
        String password = (String)getPassword().getValue();
        if(null == redirect){
            redirect = new String();
        }
        try {
            if (this.serviceLocator.getExamService().adminLogin(name , password))
            {
                FacesContext.getCurrentInstance().getExternalContext().getSession(true);
                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("admin","admin");
                setRedirect("success");
                return;
            }
        } catch (ExamException e) {
            e.printStackTrace();
        }
        FacesContext.getCurrentInstance().getExternalContext().getRequestMap().put("msg","用户名和密码不匹配，请重试");
        setRedirect("failure");          
        return;
    }
    
    /*
     * print message on console
     */
    public void debug(String message){
        System.out.println(message);
    }    
    
}
